package com.project.controller;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author lyl
 * description:用户controller
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService iUserService;

    @RequestMapping("login")
    public String login(HttpServletRequest request, UserBean userBean) {
        UserBean us = iUserService.userLogin(userBean.getUsername(), userBean.getPassword());
        if (us == null) {
            //如果为null则返回no
            return "no";
        }
        //如果不为null则进行网址的跳转并添加session记录
        setUserSession(request, us);
        return "ok";
    }

    @RequestMapping("register")
    public String register(HttpServletRequest request, UserBean userBean) {
        UserBean us = iUserService.userRegister(userBean);
        System.out.println("当前注册用户：" + us);
        setUserSession(request, us);
        return "ok";
    }

    @RequestMapping("checkExist")
    public String checkExist(String username) {
        boolean flag = iUserService.checkExist(username);
        //有相同的则返回false
        if (flag) {
            return "ok";
        }
        return "no";
    }

    @RequestMapping("getUserSession")
    public UserBean getUserSession(HttpServletRequest request) {
        UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");
        return userBean;
    }


    /**
     * 将用户信息上传至session中
     *
     * @param userBean
     */
    public void setUserSession(HttpServletRequest request, UserBean userBean) {
        HttpSession session = request.getSession();
        session.setAttribute("userBean", userBean);
        if (session.isNew()) {
            System.out.println("创建session成功" + session.getId());
        } else {
            System.out.println("已有session" + session.getId());
        }
    }

    @RequestMapping("outAccount")
    public String outAccount(HttpServletRequest request) {
        //摧毁当前session
        request.getSession().invalidate();
        return "ok";
    }

}
